//获取应用实例
const app = getApp()
//计数器
let interval = null;
//值越大旋转时间越长  即旋转速度
const intime = 50;

Page({
  data: {
    award_list: [],
    color: [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5],
    btnconfirm: '/images/dianjichoujiang.png',
    clickLuck: 'clickLuck',
    lotteryCode: '', // 抽奖码
    luckPosition: 0,
    show_code_dialog: false, // 抽奖提示
    show_lottery_dialog: false, // 中奖提示
    show_update_dialog: false, // 完善领奖人信息提示
    // 领奖人信息
    name: '',
    telephone: '',
    room_no: '',
    // 奖品信息
    award: {},
  },

  onLoad:function() {
    wx.showLoading({ title: '加载中...' });
    this.fetchAwardList().then(res => {
      console.log(res);
      const { awardList, lotteryRecord } = res;
      this.setData({ award_list: awardList || [] });
      if (lotteryRecord && lotteryRecord.name) {
        this.setData({
          award: { name: lotteryRecord.award_name, lottery_code: lotteryRecord.lottery_code, lottery_time: lotteryRecord.created_time },
          name: lotteryRecord.name,
          telephone: lotteryRecord.telephone,
          room_no: lotteryRecord.room_no
        });
      }
      return res;
    }).then(res => {
      this.loadAnimation();
      wx.hideLoading();
    }).catch(err => {
      console.error('fetchAwardList Error', err);
      wx.showToast({ title: '网络异常', icon: 'error' });
    });
  },

  /**
   * 获取奖品信息
   */
  fetchAwardList: function () {
    const promise = wx.cloud.callFunction({ name: 'fetchAwardList' }).then(res => {
      return res.result;
    });
    return promise;
  },


  /**
   * 点击抽奖
   */
  clickLuck: function() {
    // 提示输入抽奖码
    this.setData({ show_code_dialog: true });
  },

  /**
   * 输入抽奖码弹框 - 取消
   */
  onCodeDialogCancel: function() {
    this.setData({ show_code_dialog: false, lotteryCode: '' });
  },

  /**
   * 输入抽奖码弹框 - 确认
   */
  onCodeDialogConfirm: function() {
    const { lotteryCode } = this.data;
    if (!lotteryCode) {
      wx.showToast({ title: '请填写抽奖码', icon: 'none' });
      return false;
    }
    this.setData({ show_code_dialog: false, lotteryCode: '' }, () => {
      this.startLottery(lotteryCode);
    });
  },

  /**
   * 中奖提示框取消
   */
  onLotteryDialogCancel: function() {
    this.setData({
      show_lottery_dialog: false,
      name: '',
      telephone: '',
      room_no: '',
      btnconfirm: '/images/dianjichoujiang.png',
      clickLuck: 'clickLuck'
    });
  },

  /**
   * 中奖提示框确定
   */
  onLotteryDialogConfirm: function() {
    const { name, telephone, room_no, award } = this.data;
    if (!name) {
      wx.showToast({ title: '请输入姓名', icon: 'error'});
      return;
    }
    if (!telephone) {
      wx.showToast({ title: '请输入手机号', icon: 'error'});
      return;
    }
    const phoneReg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if (!phoneReg.test(telephone)) {
      wx.showToast({ title: '手机号不正确', icon: 'error'});
      return;
    }
    if (!room_no) {
      wx.showToast({ title: '请输入房间号', icon: 'error'});
      return;
    }
    // 提交领奖人信息
    wx.showLoading({ title: '提交中...' });
    const options = {
      name, telephone, room_no, award,
    };
    wx.cloud.callFunction({ name: 'updateHonoreeInfo', data: options }).then(res => {
      console.log(res);
      this.setData({
        show_lottery_dialog: false,
        btnconfirm: '/images/dianjichoujiang.png',
        clickLuck: 'clickLuck'
      });
      wx.showToast({ title: '保存成功' });
    }).catch(err => {
      console.error('onLotteryDialogConfirm Error', err);
      wx.showToast({ title: '网络异常', icon: 'error' });
    });
  },

  /**
   * 开始抽奖
   * @param {String} lotteryCode 抽奖码
   */
  startLottery: function(lotteryCode) {
    // 获取中奖位置信息
    wx.showLoading({ title: '抽奖中..' });
    const options = { code: lotteryCode, version: '2.0.0' };
    wx.cloud.callFunction({ name: 'verifyLotteryCode', data: options })
      .then(res => {
        console.log(res.result);
        const { status, code, message, luckPosition, realLuckPosition } = res.result;
        if (status !== 0) throw { code, message };
        // 设置按钮不可点击
        this.setData({ luckPosition, realLuckPosition, btnconfirm: '/images/dianjichoujiangd.png', clickLuck: '' });
        wx.hideLoading();
        return res.result;
      })
      .then(res => { // 启动转盘
        const { luckPosition } = res;
        //清空计时器
        clearInterval(interval);
        let index = 0;
        console.log(this.data.color[0]);
        //循环设置每一项的透明度
        const that = this;
        interval = setInterval(function () {
          if (index > 7) {
            index = 0;
            that.data.color[7] = 0.5
          } else if (index != 0) {
            that.data.color[index - 1] = 0.5
          }
          that.data.color[index] = 1
          that.setData({ color: that.data.color });
          index ++;
        }, intime);
        //模拟网络请求时间  设为两秒
        const stoptime = 100;
        setTimeout(function () { that.stop(luckPosition); }, stoptime);
      })
      .catch(err => {
        console.error('startLottery Error:', err);
        wx.showToast({ title: err.message || '网络异常', icon: 'error'  });
      });
  },

  /**
   * 停止转动
   * @param {*} which 
   */
  stop: function (which){
    var e = this;
    //清空计数器
    clearInterval(interval);
    //初始化当前位置
    var current = -1;
    var color = e.data.color;
    for (var i = 0; i < color.length; i++) {
      if (color[i] == 1) {
        current = i;
      }
    }
    //下标从1开始
    var index = current + 1;
    e.stopLuck(which, index, intime, 10);
  },


/**
 * which:中奖位置
 * index:当前位置
 * time：时间标记
 * splittime：每次增加的时间 值越大减速越快
 */
  stopLuck: function (which, index, time, splittime){
    var e = this;
    //值越大出现中奖结果后减速时间越长
    var color = e.data.color;
    setTimeout(function () {
      //重置前一个位置
      if (index > 7) {
        index = 0;
        color[7] = 0.5
      } else if (index != 0) {
        color[index - 1] = 0.5
      }
      //当前位置为选中状态
      color[index] = 1
      e.setData({ color: color });
      //如果旋转时间过短或者当前位置不等于中奖位置则递归执行
      //直到旋转至中奖位置 400
      if (time < 400 || index != which) {
        //越来越慢
        splittime++;
        time += splittime;
        //当前位置+1
        index++;
        e.stopLuck(which, index, time, splittime);
      } else {
        //1秒后显示弹窗
        setTimeout(function () { e.showLuckMessage(which); }, 1000);
      }
    }, time);
  },

  /**
   * 展示中奖信息
   * @param {*} luckPosition 中奖位置
   */
  showLuckMessage: function(luckPosition) {
    const { award_list, realLuckPosition } = this.data;
    const award = award_list.find(item => item.luck_position === realLuckPosition);
    console.log('奖品', award);
    this.setData({ show_lottery_dialog: true, award_name: award.name });
  },
  
  /**
   * 开启等待抽奖动画
   */
  loadAnimation: function (){
    const that = this;
    let index = 0;
    interval = setInterval(function () {
      if (index > 7) {
        index = 0;
        that.data.color[7] = 0.5
      } else if (index != 0) {
        that.data.color[index - 1] = 0.5
      }
      that.data.color[index] = 1
      that.setData({ color: that.data.color });
      index ++;
    }, 1000);
  },

  /**
   * 查看中奖信息
   */
  showLotteryRecord: function() {
    wx.showLoading({ title: '处理中...' });
    wx.cloud.callFunction({ name: 'fetchLotteryRecord' }).then(res => {
      const record = res.result;
      console.log(res);
      // 未中奖
      if (!record.award_name) {
        wx.showToast({ title: '还未参与活动', icon: 'error' });
        return;
      }
      // 已中奖但未完善领奖人信息 -> 提示完善领奖人信息
      if (!!record.award_name && !record.name) {
        this.setData({ show_update_dialog: true });
        wx.hideLoading();
        return;
      }
      this.setData({
        award: { name: record.award_name, lottery_code: record.lottery_code, lottery_time: record.created_time },
        name: record.name,
        telephone: record.telephone,
        room_no: record.room_no
      });
      wx.hideLoading();
    }).catch(err => {
      console.error('showLotteryRecord Error', err);
      wx.showToast({ title: '网络异常', icon: 'error' });
    });
  },

  /**
   * 完善中奖人提示框-取消
   */
  onUpdateDialogCancel: function() {
    this.setData({
      show_update_dialog: false,
      name: '',
      telephone: '',
      room_no: '',
      btnconfirm: '/images/dianjichoujiang.png',
      clickLuck: 'clickLuck'
    });
  },

  /**
   * 完善中奖人提示提示框-确定
   */
  onUpdateDialogConfirm: function() {
    const { name, telephone, room_no, award } = this.data;
    if (!name) {
      wx.showToast({ title: '请输入姓名', icon: 'error'});
      return;
    }
    if (!telephone) {
      wx.showToast({ title: '请输入手机号', icon: 'error'});
      return;
    }
    const phoneReg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
    if (!phoneReg.test(telephone)) {
      wx.showToast({ title: '手机号不正确', icon: 'error'});
      return;
    }
    if (!room_no) {
      wx.showToast({ title: '请输入房间号', icon: 'error'});
      return;
    }
    // 提交领奖人信息
    wx.showLoading({ title: '提交中...' });
    const options = {
      name, telephone, room_no, award,
    };
    wx.cloud.callFunction({ name: 'updateHonoreeInfo', data: options }).then(res => {
      console.log(res);
      this.setData({
        show_update_dialog: false,
        btnconfirm: '/images/dianjichoujiang.png',
        clickLuck: 'clickLuck'
      });
      this.showLotteryRecord();
    }).catch(err => {
      console.error('onLotteryDialogConfirm Error', err);
      wx.showToast({ title: '网络异常', icon: 'error' });
    });
  },
})
